package interfaces

import (
	"context"
	"net/http"
	"strconv"
	"zxstudy.com/domain/entity"
	"zxstudy.com/application"

	"github.com/gin-gonic/gin"
)

type Cars struct {
	ca application.CarApplication
}

func NewCarApplication(ca application.CarApplication) *Cars {
	return &Cars{
		ca: ca,
	}
}

/**
 * route: /car/
 * method: post
 */
func (cars *Cars) Create(c *gin.Context) {
	var car *entity.Car
	if err := c.ShouldBindJSON(&car); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"message": err.Error(),
		})
		return
	}
	newCar, err := cars.ca.Create(context.Background(), car)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"message": err.Error(),
		})
		return
	}
	
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"car": newCar,
	})
}

/**
 * route: /car/:id
 * method: delete
 */
func (cars *Cars) Delete(c *gin.Context) {
	ctx := context.Background()
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"message": err.Error(),
		})
		return
	}
	car, err := cars.ca.Get(ctx, id)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"message": err.Error(),
		})
		return
	}
	
	if err := cars.ca.Delete(ctx, car); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"message": err.Error(),
		})
		return
	}
	
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
	})
}

/**
 * route: /car/:id
 * method: get
 */
func (cars *Cars) Get(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"message": err.Error(),
		})
		return
	}
	car, err := cars.ca.Get(context.Background(), id)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"message": err.Error(),
		})
		return
	}
	
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"car": car,
	})
}

/**
 * route: /car/
 * method: get
 */
func (cars *Cars) Cars(c *gin.Context) {
	carList, err := cars.ca.Cars(context.Background())
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"message": err.Error(),
		})
		return
	}
	
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"cars": carList,
	})
}